<?php

namespace App\Http\Controllers;

use App\Models\ImportExportFile;
use App\Models\SystemLog;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ImportExportFileController extends Controller
{
    /**
     * 获取导入导出文件列表
     */
    public function index(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'page' => 'integer|min:1',
            'per_page' => 'integer|min:1|max:100',
            'status' => ['nullable', Rule::in(['pending', 'processing', 'completed', 'failed'])],
            'operation_type' => ['nullable', Rule::in(['import', 'export'])],
            'module_name' => 'nullable|string|max:50',
            'user_id' => 'nullable|integer|exists:users,id',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $query = ImportExportFile::with('user:id,username');

        // 应用筛选条件
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('operation_type')) {
            $query->where('operation_type', $request->operation_type);
        }

        if ($request->filled('module_name')) {
            $query->where('module_name', 'like', '%' . $request->module_name . '%');
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }

        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        // 分页
        $perPage = $request->get('per_page', 15);
        $files = $query->orderBy('created_at', 'desc')->paginate($perPage);

        // 添加额外字段
        $files->getCollection()->transform(function ($file) {
            return [
                'id' => $file->id,
                'original_name' => $file->original_name,
                'file_type' => $file->file_type,
                'file_size' => $file->file_size,
                'file_size_formatted' => $file->file_size_formatted,
                'operation_type' => $file->operation_type,
                'operation_type_label' => $file->operation_type_label,
                'module_name' => $file->module_name,
                'operation_description' => $file->operation_description,
                'status' => $file->status,
                'status_label' => $file->status_label,
                'progress_percentage' => $file->progress_percentage,
                'total_records' => $file->total_records,
                'success_records' => $file->success_records,
                'failed_records' => $file->failed_records,
                'error_message' => $file->error_message,
                'user_name' => $file->user_name,
                'created_at' => $file->created_at,
                'processed_at' => $file->processed_at,
                'can_download' => $this->canDownloadFile($file),
                'can_delete' => $file->canBeDeleted(),
            ];
        });

        return response()->json([
            'success' => true,
            'message' => '获取成功',
            'data' => $files
        ]);
    }

    /**
     * 获取单个导入导出文件详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        $file = ImportExportFile::with('user:id,username')->find($id);

        if (!$file) {
            return response()->json([
                'success' => false,
                'message' => '文件不存在'
            ], 404);
        }

        // 记录访问日志
        SystemLog::log(
            'view_import_export_file',
            'file',
            '查看导入导出文件详情',
            $request->user()->id,
            'ImportExportFile',
            $file->id,
            ['file_id' => $file->id, 'file_name' => $file->original_name],
            'info'
        );

        return response()->json([
            'success' => true,
            'message' => '获取成功',
            'data' => [
                'id' => $file->id,
                'original_name' => $file->original_name,
                'stored_name' => $file->stored_name,
                'file_path' => $file->file_path,
                'file_type' => $file->file_type,
                'mime_type' => $file->mime_type,
                'file_size' => $file->file_size,
                'file_size_formatted' => $file->file_size_formatted,
                'file_extension' => $file->file_extension,
                'operation_type' => $file->operation_type,
                'operation_type_label' => $file->operation_type_label,
                'module_name' => $file->module_name,
                'operation_description' => $file->operation_description,
                'status' => $file->status,
                'status_label' => $file->status_label,
                'progress_percentage' => $file->progress_percentage,
                'total_records' => $file->total_records,
                'success_records' => $file->success_records,
                'failed_records' => $file->failed_records,
                'error_message' => $file->error_message,
                'error_details' => $file->error_details,
                'filter_conditions' => $file->filter_conditions,
                'export_fields' => $file->export_fields,
                'import_mapping' => $file->import_mapping,
                'user_name' => $file->user_name,
                'user_ip' => $file->user_ip,
                'user_agent' => $file->user_agent,
                'created_at' => $file->created_at,
                'updated_at' => $file->updated_at,
                'processed_at' => $file->processed_at,
                'can_download' => $this->canDownloadFile($file),
                'can_delete' => $file->canBeDeleted(),
            ]
        ]);
    }

    /**
     * 下载导入导出文件
     */
    public function download(Request $request, $id)
    {
        $file = ImportExportFile::find($id);

        if (!$file) {
            return response()->json([
                'success' => false,
                'message' => '文件不存在'
            ], 404);
        }

        // 检查是否可以下载
        if (!$this->canDownloadFile($file)) {
            return response()->json([
                'success' => false,
                'message' => '无权下载此文件'
            ], 403);
        }

        // 检查文件是否存在
        $filePath = 'private/import_export/' . $file->stored_name;
        if (!Storage::disk('local')->exists($filePath)) {
            return response()->json([
                'success' => false,
                'message' => '文件不存在或已损坏'
            ], 404);
        }

        // 记录下载日志
        SystemLog::log(
            'download_import_export_file',
            'file',
            '下载导入导出文件',
            $request->user()->id,
            'ImportExportFile',
            $file->id,
            [
                'file_id' => $file->id,
                'file_name' => $file->original_name,
                'file_size' => $file->file_size,
                'user_ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ],
            'info'
        );

        // 返回文件下载响应
        return Storage::disk('local')->download(
            $filePath,
            $file->original_name,
            ['Content-Type' => $file->mime_type]
        );
    }

    /**
     * 获取文件统计信息
     */
    public function statistics(Request $request): JsonResponse
    {
        $user = $request->user();

        // 基本统计
        $stats = [
            'total_files' => ImportExportFile::count(),
            'my_files' => ImportExportFile::where('user_id', $user->id)->count(),
            'completed_files' => ImportExportFile::where('status', 'completed')->count(),
            'failed_files' => ImportExportFile::where('status', 'failed')->count(),
            'processing_files' => ImportExportFile::where('status', 'processing')->count(),
            'import_files' => ImportExportFile::where('operation_type', 'import')->count(),
            'export_files' => ImportExportFile::where('operation_type', 'export')->count(),
        ];

        // 按模块统计
        $moduleStats = ImportExportFile::selectRaw('module_name, COUNT(*) as count')
            ->groupBy('module_name')
            ->orderBy('count', 'desc')
            ->get();

        // 最近7天的统计
        $recentStats = ImportExportFile::where('created_at', '>=', now()->subDays(7))
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return response()->json([
            'success' => true,
            'message' => '获取统计信息成功',
            'data' => [
                'basic_stats' => $stats,
                'module_stats' => $moduleStats,
                'recent_stats' => $recentStats
            ]
        ]);
    }

    /**
     * 检查用户是否有权限下载文件
     */
    private function canDownloadFile(ImportExportFile $file): bool
    {
        $user = request()->user();

        // 管理员可以下载所有文件
        if ($user->hasRole('admin') || $user->hasRole('super_admin')) {
            return true;
        }

        // 用户只能下载自己创建的文件
        return $file->user_id === $user->id;
    }
}
